package com.tedu.egweibo2.base.exception;

import com.tedu.egweibo2.base.response.JsonResult;
import com.tedu.egweibo2.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        String data = ex.getFieldError().getDefaultMessage();
        log.error("doHandleMethodArgumentNotValidException: " + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }

    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex) {
        String str = ex.getMessage();
        String[] result = str.split(":");
        String data = result[1].trim();
        log.error("doHandleConstraintViolationException: " + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }

    @ExceptionHandler
    public JsonResult deHandleNotLoggedInException(NotLoggedInException ex) {
        String data = ex.getMessage();
        log.error("RuntimeException: " + data);
        return new JsonResult(StatusCode.NOT_LOGIN, data);
    }
}
